<template>
  <div class="main-layout">
    <!-- 根据导航模式动态加载布局 -->
    <component :is="currentLayout" />
    
    <!-- 命令面板 -->
    <CommandPanel v-model="commandPanelVisible" />
    
    <!-- 全局搜索 -->
    <GlobalSearch v-model="globalSearchVisible" />
    
    <!-- 导航设置 -->
    <NavigationSettings v-model="settingsVisible" />
    
    <!-- 快捷键提示浮窗 -->
    <transition name="fade">
      <div v-if="showShortcutHint" class="shortcut-hint">
        <div class="hint-content">
          <div class="hint-icon">
            <el-icon size="24"><InfoFilled /></el-icon>
          </div>
          <div class="hint-info">
            <div class="hint-title">快捷键提示</div>
            <div class="hint-desc">
              按 <kbd>Ctrl+K</kbd> 打开命令面板，<kbd>Ctrl+/</kbd> 全局搜索
            </div>
          </div>
          <el-button text @click="closeShortcutHint">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
import { useNavigationStore } from '@/stores/navigation'
import { useUserStore } from '@/stores/user'
import CommandPanel from '@/components/Navigation/CommandPanel.vue'
import GlobalSearch from '@/components/Navigation/GlobalSearch.vue'
import NavigationSettings from '@/components/Navigation/NavigationSettings.vue'
import { ElMessage } from 'element-plus'
import { InfoFilled, Close } from '@element-plus/icons-vue'

const router = useRouter()
const navigationStore = useNavigationStore()
const userStore = useUserStore()

// 懒加载布局组件
const ClassicLayout = defineAsyncComponent(() => import('./ClassicLayout.vue'))
const TopbarLayout = defineAsyncComponent(() => import('./TopbarLayout.vue'))
const WorkspaceLayout = defineAsyncComponent(() => import('./WorkspaceLayout.vue'))
const PieMenuLayout = defineAsyncComponent(() => import('./PieMenuLayout.vue'))
const DockLayout = defineAsyncComponent(() => import('./DockLayout.vue'))
const CardLayout = defineAsyncComponent(() => import('./CardLayout.vue'))
const SmartSearchLayout = defineAsyncComponent(() => import('./SmartSearchLayout.vue'))
const Win10Layout = defineAsyncComponent(() => import('./Win10Layout.vue'))
const Win8Layout = defineAsyncComponent(() => import('./Win8Layout.vue'))
const FloatingPanelLayout = defineAsyncComponent(() => import('./FloatingPanelLayout.vue'))
const GestureNavigationLayout = defineAsyncComponent(() => import('./GestureNavigationLayout.vue'))
const AIAssistantLayout = defineAsyncComponent(() => import('./AIAssistantLayout.vue'))
const IntelligentNavLayout = defineAsyncComponent(() => import('./IntelligentNavLayout.vue'))
const SmartNavigationLayout = defineAsyncComponent(() => import('./SmartNavigationLayout.vue'))

// 响应式数据
const settingsVisible = ref(false)
const globalSearchVisible = ref(false)
const showShortcutHint = ref(false)

// 计算属性
const currentLayout = computed(() => {
  const mode = navigationStore.mode
  const layoutMap = {
    'classic': ClassicLayout,
    'topbar': TopbarLayout,
    'workspace': WorkspaceLayout,
    'command': WorkspaceLayout, // 命令模式使用工作台布局
    'pie-menu': PieMenuLayout, // 圆形菜单导航
    'mac-launchpad': PieMenuLayout, // Mac Launchpad导航（复用PieMenuLayout，已改造）
    'dock': DockLayout, // Dock栏导航
    'card': CardLayout, // 卡片式导航
    'smart-search': SmartSearchLayout, // 智能搜索导航
    'win10': Win10Layout, // Windows 10 风格导航
    'win8': Win8Layout, // Windows 8 风格导航
    'floating-panel': FloatingPanelLayout, // 浮动面板导航
    'gesture': GestureNavigationLayout, // 手势导航
    'ai-assistant': AIAssistantLayout, // AI助手导航
    'intelligent': IntelligentNavLayout, // 智能导航系统
    'smart-navigation': SmartNavigationLayout // 智能导航系统
  }
  return layoutMap[mode] || ClassicLayout
})

const commandPanelVisible = computed({
  get: () => navigationStore.commandPanelVisible,
  set: (val) => {
    if (val !== navigationStore.commandPanelVisible) {
      navigationStore.toggleCommandPanel()
    }
  }
})

// 全局快捷键处理
const handleGlobalKeydown = (e) => {
  // Ctrl+K 打开命令面板
  if (e.ctrlKey && e.key === 'k') {
    e.preventDefault()
    navigationStore.toggleCommandPanel()
  }
  // Ctrl+/ 打开全局搜索
  else if (e.ctrlKey && e.key === '/') {
    e.preventDefault()
    globalSearchVisible.value = true
  }
  // Ctrl+B 切换侧边栏
  else if (e.ctrlKey && e.key === 'b') {
    e.preventDefault()
    if (navigationStore.mode === 'classic' || navigationStore.mode === 'topbar') {
      navigationStore.toggleSidebar()
    }
  }
  // Ctrl+H 返回首页
  else if (e.ctrlKey && e.key === 'h') {
    e.preventDefault()
    window.location.href = '/'
  }
  // Ctrl+Shift+D 切换主题
  else if (e.ctrlKey && e.shiftKey && e.key === 'D') {
    e.preventDefault()
    const darkMode = !navigationStore.settings.darkMode
    navigationStore.updateSettings({ darkMode })
  }
  // F1 显示帮助
  else if (e.key === 'F1') {
    e.preventDefault()
    showShortcutHint.value = true
  }
}

// 监听自定义事件
const handleShowSettings = () => {
  settingsVisible.value = true
}

const handleShowGlobalSearch = () => {
  globalSearchVisible.value = true
}

const closeShortcutHint = () => {
  showShortcutHint.value = false
  localStorage.setItem('shortcut-hint-closed', 'true')
}

// 生命周期
onMounted(() => {
  // 二次验证登录状态（防御性编程）
  checkLoginStatus()
  
  // 加载导航设置
  navigationStore.loadFromServer()
  
  // 如果当前路由是 Win10 桌面，确保使用 Win10 布局
  if (router.currentRoute.value.path === '/win10/desktop' && navigationStore.mode !== 'win10') {
    console.log('自动切换到 Win10 导航模式')
    navigationStore.setMode('win10')
  }
  
  // 添加全局快捷键监听
  document.addEventListener('keydown', handleGlobalKeydown)
  
  // 添加自定义事件监听
  window.addEventListener('show-navigation-settings', handleShowSettings)
  window.addEventListener('show-global-search', handleShowGlobalSearch)
  
  // 首次访问显示快捷键提示
  const hintClosed = localStorage.getItem('shortcut-hint-closed')
  if (!hintClosed) {
    setTimeout(() => {
      showShortcutHint.value = true
    }, 2000)
    
    // 5秒后自动关闭
    setTimeout(() => {
      showShortcutHint.value = false
    }, 7000)
  }
  
  // 应用主题
  if (navigationStore.settings.darkMode) {
    document.documentElement.classList.add('dark')
  }
  
  // 应用主题色
  if (navigationStore.settings.themeColor) {
    document.documentElement.style.setProperty('--el-color-primary', navigationStore.settings.themeColor)
  }
})

// 检查登录状态（二次验证）
const checkLoginStatus = () => {
  const token = localStorage.getItem('token')
  const sessionId = localStorage.getItem('sessionId')
  const userInfo = localStorage.getItem('userInfo')
  
  // 检查是否有登录凭证
  if (!token && !sessionId) {
    console.warn('MainLayout: 未检测到登录凭证，即将跳转到登录页')
    ElMessage.warning('登录状态已过期，请重新登录')
    router.push('/login')
    return
  }
  
  // 检查用户信息是否存在
  if (!userInfo) {
    console.warn('MainLayout: 用户信息丢失，即将跳转到登录页')
    ElMessage.warning('用户信息丢失，请重新登录')
    // 清理登录凭证
    localStorage.removeItem('token')
    localStorage.removeItem('sessionId')
    router.push('/login')
    return
  }
  
  // 验证 store 中的登录状态
  if (!userStore.isLoggedIn) {
    console.warn('MainLayout: Store 登录状态不一致，正在修复')
    userStore.setLoggedIn(true)
  }
  
  console.log('MainLayout: 登录状态验证通过')
}

onUnmounted(() => {
  document.removeEventListener('keydown', handleGlobalKeydown)
  window.removeEventListener('show-navigation-settings', handleShowSettings)
  window.removeEventListener('show-global-search', handleShowGlobalSearch)
})
</script>

<style scoped>
.main-layout {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.shortcut-hint {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 2000;
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.hint-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
  min-width: 350px;
}

.hint-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.hint-info {
  flex: 1;
}

.hint-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.hint-desc {
  font-size: 13px;
  color: #606266;
}

.hint-desc kbd {
  padding: 2px 6px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  font-size: 12px;
  font-family: monospace;
  color: #409eff;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

/* 暗黑模式 */
:deep(.dark) .hint-content {
  background: #1f1f1f;
  border-color: #3a3a3a;
}

:deep(.dark) .hint-title {
  color: #e4e7ed;
}

:deep(.dark) .hint-desc {
  color: #c0c4cc;
}

:deep(.dark) .hint-desc kbd {
  background: #2a2a2a;
  border-color: #3a3a3a;
}
</style>

<style>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 100%;
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

#app {
  width: 100%;
  height: 100%;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f5f7fa;
}

::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

/* 暗黑模式滚动条 */
.dark ::-webkit-scrollbar-track {
  background: #1f1f1f;
}

.dark ::-webkit-scrollbar-thumb {
  background: #3a3a3a;
}

.dark ::-webkit-scrollbar-thumb:hover {
  background: #4a4a4a;
}

/* Element Plus 暗黑模式样式覆盖 */
.dark {
  background: #141414;
  color: #e4e7ed;
}

.dark .el-card {
  background: #1f1f1f;
  border-color: #3a3a3a;
  color: #e4e7ed;
}

.dark .el-dialog {
  background: #1f1f1f;
  border-color: #3a3a3a;
}

.dark .el-menu {
  background: #1f1f1f;
  color: #e4e7ed;
}

.dark .el-table {
  background: #1f1f1f;
  color: #e4e7ed;
}

.dark .el-table th {
  background: #2a2a2a;
  color: #e4e7ed;
}

.dark .el-table tr {
  background: #1f1f1f;
}

.dark .el-table tr:hover > td {
  background: #2a2a2a !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shortcut-hint {
    bottom: 16px;
    right: 16px;
    left: 16px;
  }
  
  .hint-content {
    min-width: auto;
  }
}
</style>
